<template>
  <div>
    <el-dialog
        title="请选择地图定位"
        :visible.sync="openMap"
        :close-on-click-modal="false"
        width="70%"
    >
      <div class="mapBox">
        <div class="searchBox">
          <span>按地址搜索：</span>
          <el-input
              style="width:250px;"
              placeholder="请输入关键字"
              suffix-icon="el-icon-search"
              @input="searchByKeyword"
              @focus="searchByKeyword"
              size="medium"
              v-model="keyword">
          </el-input>
          <div class="search-result" v-if="searchResult.length && isShowResult">
            <div class="result-item" v-for="item of searchResult" :key="item.id" @click="handleClickResult(item)">
              <div class="area-name">{{ item.name }}</div>
              <div class="area-address">{{ item.district + item.address }}</div>
            </div>
          </div>
        </div>
        <div id="container" style="width: 100%;height: 400px;">
        </div>
        <div style="margin-top: 30px;">
          <el-form :inline="true" :model="loc">
            <el-form-item label="经度">
              <el-input style="width: 300px;" v-model="loc.longitude" placeholder="经度"></el-input>
            </el-form-item>
            <el-form-item label="纬度">
              <el-input style="width: 300px;" v-model="loc.latitude" placeholder="纬度"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button @click="openMap = false" style="background-color:#e0e0e0;color: #343a40">取 消</el-button>
            <el-button @click="sureSelPoint" style="background-color:#303e9d;color:#eeeeee">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

window._AMapSecurityConfig = {
  securityJsCode: '4617c699fc2723880c5f7e897eb8ec51'  //填写你的安全密钥
}
export default {
  name: "initMap",
  data() {
    return {
      openMap: false,
      keyword: "",
      searchResult: [],
      isShowResult: false,
      loc: {
        longitude: '',
        latitude: ''
      },
      AMap: null,
      map: null,
    }
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    handleOpen() {
      this.initAMap()
      this.openMap = true
    },
    initAMap() {
      AMapLoader.reset()
      AMapLoader.load({
        key: "eaec2470d19b92bbe95753e566dfda1d",             //Key
        version: "2.0",
        plugins: ['AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.MarkerClusterer', 'AMap.DistrictSearch', 'AMap.ZoomControl', 'AMap.Polygon', 'AMap.Geocoder',],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.geocoder = new AMap.Geocoder()
        this.map = new AMap.Map("container", {  //设置地图容器id
          // viewMode: "3D",    //是否为3D地图模式
          resizeEnable: true,
          zoom: 12,           //初始化地图级别
          center: [112.938814, 28.228209], //初始化地图中心点位置
        });
        this.handleClick(AMap)//地图选点
        // this.map.on('click', (e) => {
        //   this.loc.latitude = e.lnglat.lat
        //   this.loc.longitude = e.lnglat.lng
        //   this.initMarket()
        // })
        var autoOptions = {
          input: "tipinput"
        };
        this.autocomplete = new AMap.AutoComplete(autoOptions);
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map
        });
      }).catch(e => {
        // console.log(e);
      })
    },
    changeValue(longitude, latitude, name, address) {
      this.isShowResult = false
      this.loc.longitude = longitude
      this.loc.latitude = latitude
      const center = new AMap.LngLat(longitude, latitude);
      // 将地图的中心点移动到指定的经纬度
      this.map.setCenter(center);
      this.marker = new AMap.Marker({
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        position: [this.loc.longitude, this.loc.latitude],
        zIndex: 103
      })
      this.map.add(this.marker)
    },
    openMapDia() {
      this.initAMap();
      this.openMap = true
    },
    sureSelPoint() {
      // if (this.loc.latitude && this.loc.longitude) {
      //   this.openMap = false
      //   this.form = {...this.form, address: this.address || this.keyword};
      // } else {
      //   this.$message.warning('请选择经纬度')
      // }
      const data = {
        latitude: this.loc.latitude,
        longitude: this.loc.longitude,
        address: this.address || this.keyword
      }
      this.$emit('addStatus', data);
      this.openMap = false
    },
    handleClick() {
      this.map.on('click', (e) => {
        let lng = e.lnglat.lng
        let lat = e.lnglat.lat
        let marker = new AMap.Marker({
          position: new AMap.LngLat(lng, lat)
        })
        this.map.clearMap()// 清除所有覆盖物（点标志）
        this.map.add(marker)// 添加点标志
        let lnglat = [lng, lat]
        let that = this
        that.geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.regeocode) {
            that.address = result.regeocode.formattedAddress;
            that.showInfoWindow(marker);//自定义信息窗体
            let thisPosition = {
              address: that.address,
              lng: lng,
              lat: lat
            };
            that.$emit("select", thisPosition)
          } else {
            that.$message.error('根据经纬度查询地址失败')
          }
        })
        this.loc.latitude = lat
        this.loc.longitude = lng
      })
    },
    showInfoWindow(marker) {
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, //是否自定义信息窗体
        content: `<div style="background-color: white;padding: 0 5px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${this.address}</div>`,
        closeWhenClickMap: true,
        zIndex: 999,
        offset: new AMap.Pixel(16, -35)
      });
      infoWindow.open(this.map, marker.getPosition());
    },
    handleClickResult(e) {
      const {location, district, address} = e
      const {lng, lat} = location || {}
      // 1. 如果当前搜索结果有经纬度, 直接在地图上选中, 并返回当前的值
      if (lng && lat) {
        this.map.clearMap() //先清空点位
        this.changeValue(lng, lat, e.name, district + address)
        this.keyword = district + address
      } else {
        this.isShowResult = false
        this.placeSearch.search(district + address);
      }
    },
    // 输入框搜索显示下拉
    searchByKeyword() {
      this.autocomplete.search(this.keyword, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          this.searchResult = result.tips.map((item) => {
            return {
              ...item,
              address: Array.isArray(item.address) ? (item.address[0] || '') : item.address
            }
          })
          this.isShowResult = true
        }
      })
    },
  }
}
</script>

<style scoped lang="less">
#container {
  width: 100%;
  height: 500px;
}

::v-deep .el-dialog__body {
  padding: 0px 20px !important;
}

.mapBox {
  position: relative;

  .searchBox {
    position: absolute;
    z-index: 111;
    top: 10px;
    left: 10px;
  }
}

.search-result {
  width: 100%;
  max-height: 300px;
  overflow-y: scroll;
  background-color: #fff;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.0600);
  box-sizing: border-box;

  .result-item {
    width: 100%;
    cursor: pointer;
    border-bottom: 2px solid #eee;
    padding: 10px 12px;

    .area-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 20px;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      line-height: 20px;
    }

    .area-address {
      color: rgba(0, 0, 0, 0.4500);
      font-size: 12px;
      line-height: 18px;
    }
  }
}
</style>